﻿using UnityEngine;
using System.Collections;

namespace UI
{
    public class FormationItemModel : UIDragDropItem
    {
        private GameObject model;
        private string modelPostion;
        public Actors actor;
        public GameObject parentBox;
        private int formationId;
        public GameObject bloodNumLabel;
        public GameObject bloodSpr;
        private Dict.DataModel.TableHero hero;
        public RenderTexture rt;
        public GameObject txt;
        


        public void Init(int formationId, string modelPostion)
        {
            
            
            bloodSpr.GetComponent<UISprite>().spriteName = "bloodBottom";
            bloodNumLabel.GetComponent<UILabel>().text = "";
            this.formationId = formationId;
            this.modelPostion = modelPostion;
            Actors tempActor = ActorManager.Instance.GetMyActorByPostion(formationId);
         //   SaveBattleHero.Instance.ClearHeroCache();
            SaveBattleHero.Instance.AddHeroForBattle(tempActor);

            if (tempActor != null)
            {

                AddHero(tempActor);
            }
            rt = new RenderTexture(256, 512, 8);
            rt.filterMode = FilterMode.Bilinear;
            rt.useMipMap = false;
            txt.GetComponent<UITexture>().mainTexture = rt;

            PageManager.Instance.GetPage<FormationPanel>().formationModelGroup.cameraList[formationId - 1].GetComponent<Camera>().targetTexture = rt;

        }
        /// <summary>
        /// 添加英雄
        /// </summary>
        /// <param name="actor"></param>
        public void AddHero(Actors actor)
        {
            gameObject.transform.parent = parentBox.transform;
            gameObject.transform.localPosition = Vector3.zero;
            RemoveHero();
            this.actor = actor;
            if (actor != null)
            {
                SaveBattleHero.Instance.AddHeroForBattle(actor);
                this.actor.formationPositionId = formationId;
                AddModel(actor);
                bloodNumLabel.GetComponent<UILabel>().text = "10000";//测试数据，随便写的
                bloodSpr.GetComponent<UISprite>().spriteName = "bloodTop";
            }
        }
        /// <summary>
        /// 移除英雄
        /// </summary>
        private void RemoveHero()
        {
            if (this.actor != null)
            {
                SaveBattleHero.Instance.DeleteHeroForBattle(actor);
                RemoveModel();
                this.actor.formationPositionId = 0;
                this.actor = null;
                bloodSpr.GetComponent<UISprite>().spriteName = "bloodBottom";
                bloodNumLabel.GetComponent<UILabel>().text = "";
            }
        }
        /// <summary>
        /// 移除模型
        /// </summary>
        private void RemoveModel()
        {
            if (model != null)
            {
                model.transform.SetParent(null);
                ResourceLoader.GetInstance().modelLoader.UnloadModel(model, hero.resName);
                Destroy(model);
                model = null;
            }
        }
        /// <summary>
        /// 添加模型
        /// </summary>
        /// <param name="actor"></param>
        private void AddModel(Actors actor)
        {

            hero = Dict.DictDataManager.Instance.tableHeroDao.GetById(actor.heroid);
            this.actor = actor;
            LoadResourceAsync();
        }
        /// <summary>
        /// 异步加载资源
        /// </summary>
        private void LoadResourceAsync()
        {
            StartCoroutine(_LoadRes());
        }
        IEnumerator _LoadRes()
        {
            yield return StartCoroutine(ResourceLoader.GetInstance().modelLoader.LoadModel(hero.resName, (asset) => {
                model = asset as GameObject;
            }));

            if (this.actor != null)
            {
                model.transform.SetParent(PageManager.Instance.GetPage<FormationPanel>().formationModelGroup.modelList[formationId - 1].transform);
                model.transform.localScale = new Vector3(1, 1, 1);
                model.transform.localPosition = new Vector3(int.Parse(modelPostion.Split(',')[0]), int.Parse(modelPostion.Split(',')[1]), int.Parse(modelPostion.Split(',')[2]));
                model.transform.localEulerAngles = new Vector3(0, 180, 0);
                model.GetComponent<LegacyAnimation>().Play("standfight", WrapMode.Loop);
                SetLayer(model, 10);
            }

        }
        /// <summary>
        /// 设置layer
        /// </summary>
        /// <param name="target"></param>
        /// <param name="layer"></param>
        private void SetLayer(GameObject target, int layer)
        {
            target.layer = layer;
            foreach (Transform t in target.transform)
            {
                SetLayer(t.gameObject, layer);
            }
        }

        /// <summary>
        /// 点击阵容面板英雄
        /// </summary>
        public void ClickFormationItem()
        {
           

            if (this.actor != null)
            {
                RemoveHero();
               
            }

            //if (formationPanel.selectActor != null && formationPanel.selectActor.formationPositionId == 0)
            //{
            //    AddHero(formationPanel.selectActor);
                
            //}
            if (FormationPanel._instance.selectActor != null && FormationPanel._instance.selectActor.formationPositionId == 0)
            {
                AddHero(FormationPanel._instance.selectActor);
               
              
            }
            else {
                
            }
            FormationPanel._instance.SetSelectActor(null);
            
        }
        /// <summary>
        /// 从面板删除英雄
        /// </summary>
        public void RemoveActorFromFormation()
        {
            
            if (this.actor != null)
            {
                
                RemoveHero();
            }
            //formationPanel.SetSelectActor(null);
            FormationPanel._instance.SetSelectActor(null);

        }

        protected override void OnDragDropRelease(GameObject surface)
        {
            FormationItemModel targerItem = surface.GetComponent<FormationItemModel>();
            if (actor != null)
            {
                if (targerItem != null && targerItem != this)
                {
                    Actors actor1 = targerItem.actor;
                    Actors actor2 = this.actor;
                    RemoveHero();
                    targerItem.RemoveHero();
                    AddHero(actor1);
                    targerItem.AddHero(actor2);
                }
                else
                {
                    gameObject.transform.parent = parentBox.transform;
                    gameObject.transform.localPosition = Vector3.zero;
                }
            }
            else
            {
                gameObject.transform.parent = parentBox.transform;
                gameObject.transform.localPosition = Vector3.zero;
            }

            base.OnDragDropRelease(surface);
        }
    }
}
